﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CachePoison
{
    static class Config
    {
        private static Semaphore semCacheConfig = new Semaphore(1, 1);

        private static string cachePoisonConfig = "cachepoison.cfg";

        public static bool ExistsConfig()
        {
            if (System.IO.File.Exists(string.Concat(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"\", cachePoisonConfig)))
                return true;
            return false;
        }

        public static string GetField(string field)
        {
            string value = string.Empty;
            FileStream fs = null;
            StreamReader sr = null;

            try
            {
                semCacheConfig.WaitOne();
                fs = new FileStream(string.Concat(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), @"\", cachePoisonConfig), FileMode.Open, FileAccess.Read);
                sr = new StreamReader(fs);

                string line = string.Empty;
                while ((line = sr.ReadLine()) != null)
                {
                    line = line.Trim();

                    if (line.StartsWith("#"))
                        continue;
                    if (string.IsNullOrEmpty(line))
                        continue;

                    if (line.Contains('='))
                    {
                        if (line.Split('=')[0] == field)
                        {
                            value = line.Split('=')[1];
                            return value;
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                if (fs != null)
                    fs.Close();

                if (sr != null)
                    sr.Close();

                semCacheConfig.Release();
            }

            return value;
        }

    }
}
